import api from "@/api/api";
import {
  SEL_CLASS_CODE,
  SEL_ACTIVE_CODE,
  SYSTEM_INFO,
  USER_INFO,
  CUSTOMER_INFO,
  CUSTOMER_HOTFIX,
  CART_KEY,
  MERCHANT_INFO,
  USER_SPECICAL_INFO
} from "./constant";
import commonSensors from "@/utils/commonSensors.js";

function onTriggerComponent(e) {
  try {
    let {
      item,
      type,
      trackData = null,
      module_name = "",
      tab_name = ""
    } = e.detail.data;
    if (trackData) sensorsTracking(trackData);
    const _typeArr = ["itemClick", "addCartClick"];
    if (item && _typeArr.includes(type)) tencentYoushuTracking(item, type, module_name, tab_name);
  } catch (e) {
    console.log("home-onTriggerComponent-error:", e)
  }
}

/**
 * 腾讯有数埋点
 * @param {Object} item
 * @param {String} type
 * @param {Any} module_name
 * @param {Any} tab_name
 */
async function tencentYoushuTracking(item, type, module_name, tab_name) {
  try {
    let merchantInfo = uni.getStorageSync('merchantInfo');
    const _openOuterItemId = uni.getStorageSync('openOuterItemId');
    const _youshuOpencc = uni.getStorageSync('youshuOpencc');
    if(!item.skuCodes){
      item = await getGoodsDetails(merchantInfo, item);
    }
    if (type == 'itemClick') {
      commonSensors.PLPProductClick(item, "", module_name, tab_name);
			const spuid = !!_openOuterItemId ? item.outerItemId : !!_youshuOpencc ? item.frontProperties[0].frontCode ?.toString() : item.itemCode?.toString();
			const spuname = !!_youshuOpencc ? item.itemName + item.frontProperties?.[0].valueName : item.itemName // 若商品无spu_name时，可传sku_name信息
      getApp().globalData.$sr.track('trigger_sku_component', {
        "sku": {
          "sku_id": item.skuCodes[0]?.toString(),
          "sku_name": item.itemName
        },
        "spu": {
          "spu_id": spuid || item.skuCodes[0]?.toString(),
          "spu_name": spuname || item.itemName
        },
        "sku_category": [{
          "sku_cat_id": item.categoryId?.toString(),
          "sku_cat_name": "11",
          "sku_parent_cat_id": "null" // 若已是顶级类目，传"null"
        }],
        "shipping_shop": {
          "shipping_shop_id": merchantInfo.cloudMerchantId + '', // 到家类型对接智慧零售入口必传
          "shipping_shop_name": "THE MACALLAN EBOUTIQUE麦卡伦" // 到家类型对接智慧零售入口必传
        },
        // "sale": {
        // 	"original_price": parsefloor(item.price), // 对接智慧零售入口必传
        // 	"current_price": parsefloor(item.markingPrice) // 对接智慧零售入口必传
        // },
        "primary_image_url": item.skuImageUrl
      });
    } else if (type == "addCartClick") {
      commonSensors.addToCartMF(item, 1, ['常规']);
      //这里是购物车
      getApp().globalData.$sr.track('add_to_cart', {
        "action_type": 'append_to_cart',
        "sku": {
          "sku_id": item.skuCodes[0].toString(),
          "sku_name": item.itemName
        },
        "spu": {
          "spu_id": !!_openOuterItemId ? item.outerItemId : !!_youshuOpencc ? item.frontProperties[0].frontCode
            ?.toString() : item.itemCode?.toString(),
          "spu_name": !!_youshuOpencc ? item.itemName + item.frontProperties?.[0].valueName : item
            .itemName // 若商品无spu_name时，可传sku_name信息
        },
        "sku_category": [{
          "sku_cat_id": item.categoryId?.toString(),
          "sku_cat_name": "11",
          "sku_parent_cat_id": "null" // 若已是顶级类目，传"null"
        }],
        "shipping_shop": {
          "shipping_shop_id": merchantInfo.cloudMerchantId + '', // 到家类型对接智慧零售入口必传
          "shipping_shop_name": "THE MACALLAN EBOUTIQUE麦卡伦" // 到家类型对接智慧零售入口必传
        },
        // "sale": {
        // 	"original_price": parsefloor(item.price), // 对接智慧零售入口必传
        // 	"current_price": parsefloor(item.markingPrice) // 对接智慧零售入口必传
        // },
        "sku_num": 1,
        "primary_image_url": item.skuImageUrl
      })
    }
  } catch (e) {
    console.log("###### commonUtoolsTrack-tencentYoushuTracking-error:", e)
  }
}

/**
 * 神策埋点
 * @param {Object} trackData
 */
function sensorsTracking(trackData) {
  try {
    const _trackData = JSON.parse(trackData);
    if (_trackData.name) {
      if (_trackData.type === 'click') commonSensors.lithaTrack.cTrack(_trackData.name, _trackData.data);
      if (_trackData.type === 'view') commonSensors.lithaTrack.crTrack(_trackData.name, _trackData.data);
    } else {
      console.log("##### 神策埋点失败-埋点名称不存在 #####");
    }
  } catch (e) {
    console.log("###### commonUtoolsTrack-sensorsTracking-error:", e)
  }
}

async function getGoodsDetails(merchantInfo, itemObj){
  try{
    const json = await api.goodsDetail({
    		query: {
    			merchant_id: merchantInfo.cloudMerchantId,
    			store_id: merchantInfo.cloudMerchantStoreId
    		}
    	},
    	itemObj.itemId
    );
    if (json.code === 1000 && json.data) {
    	let data = json.data;
      const _skucode = data?.skus[0]?.skuCode || "";
      itemObj.skuCodes = [_skucode];
      itemObj.itemName = data.itemName || "";
      itemObj.frontProperties = data.frontProperties || "";
      itemObj.categoryId = data.categoryId || "";
      itemObj.skuImageUrl =  data.skus[0]?.skuImageUrl || "";
      itemObj.outerItemId = data.outerItemId || "";
      itemObj.valueName = data.frontProperties[0]?.valueName;
    }
    return itemObj;
  }catch(e){
    return itemObj;
  }
}

module.exports = {
  tencentYoushuTracking,
  sensorsTracking,
  onTriggerComponent
};
